//定义小蛇的构造函数  自调用函数 --自执行函数
;
(function() {
    var arrSnake = []
        //小蛇的构造函数
    function Snake(width, height, dirctor) {
        this.width = width || '20';
        this.height = height || '20';
        this.dirctor = dirctor || 'right'
            //小蛇的身体,默认初始
        this.body = [{
                x: 3,
                y: 1,
                color: 'red'
            }, //头
            {
                x: 2,
                y: 1,
                color: 'orange'
            }, //身体
            {
                x: 1,
                y: 1,
                color: 'orange'
            }, //身体
        ]
    }
    // 创建小蛇
    Snake.prototype.init = function(map) {
            remove()
            for (var i = 0; i < this.body.length; i++) {
                //创建小蛇身体
                var div = document.createElement('div')
                    //为div添加样式属性
                div.style.width = this.width + 'px'
                div.style.height = this.height + 'px'
                div.style.backgroundColor = this.body[i].color;
                div.style.position = 'absolute';
                div.style.top = this.body[i].y * this.height + 'px'
                div.style.left = this.body[i].x * this.width + 'px'
                    //把小蛇的身体添加到map中
                map.appendChild(div)
                arrSnake.push(div)
            }
        }
        //小蛇移动
    Snake.prototype.move = function(map, food) {
            //修改小蛇身体的移动
            var i = this.body.length - 1; //2
            for (; i > 0; i--) {
                this.body[i].x = this.body[i - 1].x
                this.body[i].y = this.body[i - 1].y
            }
            //修改舌头的移动
            switch (this.dirctor) {
                case 'right':
                    this.body[0].x += 1;
                    break;
                case 'left':
                    this.body[0].x -= 1;
                    break;
                case 'top':
                    this.body[0].y -= 1;
                    break;
                case 'bottom':
                    this.body[0].y += 1;
                    break;
            }
            //判断小蛇有没有迟到食物
            var headX = this.body[0].x * this.width
            var headY = this.body[0].y * this.height
            console.log(headX, food.x)
            console.log(headY, food.y)
            if (headX === food.x && headY === food.y) {
                //获取小蛇最后的尾巴
                var last = this.body[this.body.length - 1]
                    //把蛇尾复制加到小蛇的身体中
                this.body.push({
                    x: last.x,
                    y: last.y,
                    color: last.color
                })
                food.init(map)
            }

        }
        //删除之前的小蛇
    function remove() {
        var i = arrSnake.length - 1; //2
        for (; i >= 0; i--) {
            //DOM操作，在父元素中删除子元素
            arrSnake[i].parentNode.removeChild(arrSnake[i])
            arrSnake.splice(i, 1)
        }
    }
    window.Snake = Snake
}())